package com.znyj.cloud.chain.httphandler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * Created by gaoliwei on 15-1-14.
 */
@Component
public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    private static SslContext sslContext;

    @Resource
    private HttpDispatcherHandler httpDispatcherHandler;

    public ServerInitializer() {
    }

    public ServerInitializer(SslContext sslContext) {
        this.sslContext = sslContext;
    }

    public static void setSslContext(SslContext sslContext) {
        ServerInitializer.sslContext = sslContext;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        if (sslContext != null) {
            p.addLast(sslContext.newHandler(ch.alloc()));
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
//        p.addLast(httpContentHandler);
        p.addLast(httpDispatcherHandler);
    }
}
